/**
 * Created by qunxing.du on 2016/7/28.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.gdyc.job;

import com.hw.one.collect.gdyc.data.GdRawFiveMinDataService;
import com.hw.one.collect.gdyc.memento.GdycCareTaker;
import com.hw.one.collect.gdyc.memento.GdycMemento;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 广德扬尘容错处理job
 */
@Component
public class GdycErrorHandlerJob extends GdJob {
    private static Logger log = Logger.getLogger(GdycErrorHandlerJob.class);
    @Resource
    private GdRawFiveMinDataService gdRawFiveMinDataService;

    @Override
    protected void start() {
        Map<Integer, GdycMemento> mementos = GdycCareTaker.newInstance().getAll();
        Collection<GdycMemento> collection = mementos.values();
        log.debug("广德备忘录数量：" + collection.size());
        for (Iterator<GdycMemento> i = collection.iterator(); i.hasNext(); ) {
            GdycMemento memento = i.next();
            String startTime = memento.getStartTime();
            String endTime = memento.getEndTime();
            int count = memento.getCount();
            log.debug("备忘录数据：" + startTime + "|" + endTime + "|" + count);
            if (isAllowExecute(endTime,count)) {
                Map<String, Object> map = new HashMap<>();

                map.put("startTime", startTime);
                map.put("endTime", endTime);
                //拉取数据
                String data = gdRawFiveMinDataService.pull(map);
                //推送数据
                push(data, startTime, endTime);
            }
        }
    }

    /**
     * 是否已到允许执行的时间
     *
     * @param endTime
     * @return
     */
    private boolean isAllowExecute(String endTime,int count) {
        if(0 == count){
            return false;
        }
        Date lastDate = null;//最近一次执行的结束日期
        try {
            lastDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
        } catch (ParseException e) {
            log.error(e);
        }
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, -GD_FIVEMIN_FAULT_TOLERANT_INTERVAL*count);
        Date intervalDate = c.getTime();//间隔时间差
        return intervalDate.after(lastDate);
    }
}
